package com.nowcoder.community.service;

import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.utils.CommonUtil;
import com.nowcoder.community.utils.ConstantUtil;
import com.nowcoder.community.utils.MailClient;
import com.nowcoder.community.utils.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: shuhuang
 * @description:
 * @Date: 2022/10/2 20:57
 * @Version java version 1.8
 */
@Service
public class UserService {
    @Autowired(required = false)
    private UserMapper userMapper;
    /**
     * @Autowired(required = false)
     * private LoginTicketMapper loginTicketMapper;
     **/
    @Autowired
    private MailClient mailClient;
    @Autowired
    private TemplateEngine templateEngine;
    @Value("${community.path.domain}")
    private String domain;
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Autowired
    private RedisTemplate redisTemplate;

    public User findUserById(Integer id) {
//        return userMapper.selectById(id);
        User user = this.getCache(id);
        if (user == null) {
            user = this.initCache(id);
        }
        return user;
    }

    public User findUserByName(String username) {
        return userMapper.selectByName(username);
    }

    public User findUserByEmail(String email) {
        return userMapper.selectByEmail(email);
    }

    public int insertUser(User user) {
        return userMapper.insertUser(user);
    }

    public int updateStatus(Integer id, int status) {
        return userMapper.updateStatus(id, status);
    }

    public int updateHeaderUrl(Integer id, String headerUrl) {
        return userMapper.updateHeaderUrl(id, headerUrl);
    }

    public int updatePassword(Integer id, String password) {
        return userMapper.updatePassword(id, password);
    }

    /**
     * 注册业务处理
     */
    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();
        //空值处理
        if (user == null) {
            throw new IllegalArgumentException("传入方法的参数不能为空！");
        }
        if (!StringUtils.hasText(user.getUsername())) {
            map.put("usernameMsg", "用户名不能为空！");
            return map;
        }
        if (!StringUtils.hasText(user.getPassword())) {
            map.put("passwordMsg", "用户密码不能为空！");
            return map;
        }
        if (!StringUtils.hasText(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空！");
            return map;
        }
        //验证账号
        User user1 = userMapper.selectByName(user.getUsername());
        if (user1 != null) {
            map.put("usernameMsg", "该用户名已被注册！");
            return map;
        }
        user1 = userMapper.selectByEmail(user.getEmail());
        if (user1 != null) {
            map.put("emailMsg", "该邮箱已被注册！");
            return map;
        }
        //注册用户
        user.setSalt(CommonUtil.generateUUID().substring(0, 5));
        user.setPassword(CommonUtil.MD5(user.getPassword() + user.getSalt()));
        user.setStatus(0);
        user.setType(0);
        user.setActivationCode(CommonUtil.generateUUID());
        user.setCreateTime(new Date());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        userMapper.insertUser(user);
        //给前端thymeleaf页面传递一些参数，用来激活邮件
        Context context = new Context();
        context.setVariable("mail", user.getUsername());
        String activeUrl = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("activeUrl", activeUrl);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.mailSend(user.getEmail(), "激活牛客账号", content);
        return map;
    }

    /**
     * 激活账号业务处理（即修改status=1）
     */
    public int activation(int userId, String code) {
        User user = userMapper.selectById(userId);
        if (user.getStatus() == 1) {
            return ConstantUtil.ACTIVATION_REPEAT;
        } else if (user.getActivationCode().equals(code)) {
            userMapper.updateStatus(userId, 1);
            //清除缓存
            this.clearCache(userId);
            return ConstantUtil.ACTIVATION_SUCCESS;
        } else {
            return ConstantUtil.ACTIVATION_FAILURE;
        }
    }

    /**
     * 登录业务处理（例：过期时间12个小时：3600*12）
     */
    public Map<String, Object> login(String username, String password, long expiredSeconds) {
        Map<String, Object> map = new HashMap<>();
        //空值处理
        if (username == null || ("").equals(username)) {
            map.put("usernameMsg", "用户名不能为空！");
            return map;
        }
        if (!StringUtils.hasText(password)) {
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }
        //验证账号
        User user = userMapper.selectByName(username);
        if (user == null) {
            map.put("usernameMsg", "该账号不存在！");
            return map;
        }
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活！");
            return map;
        }
        String md5Pw = CommonUtil.MD5(password + user.getSalt());
        if (!user.getPassword().equals(md5Pw)) {
            map.put("passwordMsg", "密码不正确！");
            return map;
        }
        //生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommonUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));
        //loginTicketMapper.insertLoginTicket(loginTicket);
        //将ticket存入redis
        String ticketKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(ticketKey, loginTicket);

        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    /**
     * 用户退出登录，将登录凭证修改为失效状态
     */
    public void logout(String ticket) {
//        loginTicketMapper.updateStatus(ticket, 1);
        String ticketKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(ticketKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(ticketKey, loginTicket);
    }

    /**
     * 通过获取到cookie中的值，查询LoginTicket
     */
    public LoginTicket findLoginTicket(String ticket) {
//        return loginTicketMapper.selectTicket(ticket);
        String ticketKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(ticketKey);

    }

    /**
     * 账户设置中的上传文件业务处理
     */
    public int updateHeaderImage(int userId, String headerUrl) {
        int rows = userMapper.updateHeaderUrl(userId, headerUrl);
        //清除缓存
        this.clearCache(userId);
        return rows;
    }

    /**
     * 用户修改密码业务
     */
    public Map<String, Object> alterPassword(int userId, String oldPassword, String newPassword) {
        Map<String, Object> map = new HashMap<>();
        //验证原密码是否与当前用户一致
        User user = userMapper.selectById(userId);
        String md5OldPw = CommonUtil.MD5(oldPassword + user.getSalt());
        if (!user.getPassword().equals(md5OldPw)) {
            map.put("errorMsg", "密码错误，请重试！");
            return map;
        }
        if (oldPassword.equals(newPassword)) {
            map.put("tipMsg", "新密码不能与原密码重复，请重试！");
            return map;
        }
        String md5NewPw = CommonUtil.MD5(newPassword + user.getSalt());
        //更新当前用户密码
        userMapper.updatePassword(userId, md5NewPw);
        return map;
    }

    /**
     * 1.优先从缓存中取值
     **/
    private User getCache(int userId) {
        String userKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(userKey);
    }

    /**
     * 2.取不到时初始化缓存数据
     **/
    private User initCache(int userId) {
        User user = userMapper.selectById(userId);
        String userKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(userKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }

    /**
     * 3.当数据发生更改时，清楚缓存数据
     */
    private void clearCache(int userId) {
        String userKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(userKey);
    }

    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        User user = this.findUserById(userId);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch (user.getType()) {
                    case 1:
                        return ConstantUtil.AUTHORITY_ADMIN;
                    case 2:
                        return ConstantUtil.AUTHORITY_MODERATOR;
                    default:
                        return ConstantUtil.AUTHORITY_USER;
                }
            }
        });
        return list;
    }

}
